import {CalculateEnergy, isInArray, adaption_body, InsulateRoom} from '@/utils'
import { BluePrint, BluePrint2 } from './BLUEPRINT';
/* 房间运维核心功能原型拓展通用函数 */
export default class RoomCoreExtension extends Room {
    /*
    ** 房间内spawnID挂载模块
    ** 一共挂载三个spawnid
    */
    public mount_spawnID(spawnName:string[]):StructureSpawn[]
    {
        var spawn1 = Game.spawns[spawnName[0]];var spawn2 = Game.spawns[spawnName[1]];var spawn3 = Game.spawns[spawnName[2]]
        var spawn1_id = spawn1?spawn1.id:'';var spawn2_id = spawn2?spawn1.id:'';var spawn3_id = spawn3?spawn1.id:''
        if (!this.memory.spawn1ID) this.memory.spawn1ID = spawn1_id
        if (!spawn1) this.memory.spawn1ID = ''
        if (!this.memory.spawn2ID) this.memory.spawn2ID = spawn2_id
        if (!spawn2) this.memory.spawn2ID = ''
        if (!this.memory.spawn3ID) this.memory.spawn3ID = spawn3_id
        if (!spawn3) this.memory.spawn3ID = ''
        // 顺便将controller的id放进memory里
        if (!this.memory.controlID) this.memory.controlID = this.controller.id
        return[spawn1,spawn2,spawn3]
    }
    /* 爬虫Body自适应及孵化模块 */
    public RoleAdaption():void{
        let result = global.DicCreepFrameControl[this.name]
        const allEnergyCapacity = this.energyCapacityAvailable
        const allEnergy = this.energyAvailable
        if (!result) return
        /* 即将孵化的role */
        let spawn_role = ''
        for (var sample of Object.keys(result))
        {
            const actual_num = _.filter(Game.creeps,(creep) => creep.memory.role == result[sample].work && creep.memory.belong == this.name).length
            if (actual_num < result[sample].num)
            {
                /* 如果房间能量上限低于爬虫所需能量，就启动降级改造 */
                if(allEnergyCapacity < CalculateEnergy(result[sample].ability))
                    adaption_body(result[sample].ability,allEnergyCapacity)
                /* 如果爬虫是must,死光了且当前能量不够孵化,则启动降级改造 */
                if (allEnergy < CalculateEnergy(result[sample].ability) && actual_num==0 && result[sample].must)
                    adaption_body(result[sample].ability,allEnergy)
                // 生产优先级，优先生产must级爬虫
                if (spawn_role == '' || !result[spawn_role].must)
                {
                    spawn_role = result[sample].work
                }
            }
        }
        if (spawn_role == '') return
        /* 开始孵化流程 寻找当前房间所有可用的spawn */
        const allSpawn = this.find(FIND_STRUCTURES,{filter:{structureType:STRUCTURE_SPAWN}}) as StructureSpawn[]
        if (allSpawn.length <= 0){
            console.log("没有可出生的母巢")
            if (this.memory.roomSTATE && this.memory.roomSTATE == 'war')
                Game.notify(`房间${this.name}所有母巢均被摧毁！`)
            return
        }
        var active_spawn = []
        for (var s of allSpawn) if (!s.spawning) active_spawn.push(s)
        if (active_spawn.length <= 0) return
        // 爬虫名称隔离
        let spawnName:string
        if (this.controller.owner.username != 'superbitch') spawnName = `#${result[spawn_role].work}-${active_spawn[0].name}-${Game.time}`
        else spawnName = `${result[spawn_role].work[0]}/${Game.time}/${Math.round(Math.random()*10)}/${active_spawn[0].name}`
        active_spawn[0].spawnCreep(result[spawn_role].ability,spawnName,{memory:{
            role:result[spawn_role].work,belong:this.name,controlByFrame:result[spawn_role].controlByFrame,shard:Game.shard.name
        }})
    }

    /* 1型房间状态判断模块  只支持两种状态：war、peace */
    public identify_room_state_01(critical_tick:number = 5,peace_tick:number = 30):void{
        if (!this.memory.roomSTATE) this.memory.roomSTATE = 'peace'
        if (!Memory.whitesheets) Memory.whitesheets = []
        // 判断有没有敌对虫子，如果存活时间超过指定tick 便判定为战争状态
        var enemy_creep = this.find(FIND_HOSTILE_CREEPS,{filter: (creep)=>{return !isInArray(Memory.whitesheets,creep.owner.username)}})
        if (enemy_creep.length > 0 )
            {
                
                this.memory.peaceTick = 0
                // 如果没有激活enemy
                if (!this.memory.enemyTICK) this.memory.enemyTICK = 1
                else{ this.memory.enemyTICK += 1}
                if (this.memory.enemyTICK > critical_tick) this.memory.roomSTATE = 'war'

            }
            else
            {
            if (this.memory.peaceTick < 300)
            this.memory.peaceTick += 1
            if (this.memory.peaceTick >= peace_tick)
            {
                this.memory.roomSTATE = 'peace'
                this.memory.enemyTICK = 0
            }
        }
    }

    /* 新1型房间状态执行模块 */
    public RoomState01(roleData?:DicRoleData):void{
        if (this.memory.roomSTATE == 'war')
        {
            if (roleData) this.war_plan_02_P(roleData)
            else this.war_plan_02()
        }
        else
        {
            this.plan_C1(BluePrint)
        }
    }

    /* 2型房间状态执行模块 不新增布局，布局全由手动布置 */
    public RoomState02(roleData?:DicRoleData):void{
        if (this.memory.roomSTATE == 'war')
        {
            if (roleData) this.war_plan_02_P(roleData)
            else this.war_plan_02()
        }
        else
        {
            this.plan_C1([])
        }
    }
    public RoomState03(roleData?:DicRoleData):void{
        if (this.memory.roomSTATE == 'war')
        {
            if (roleData) this.war_plan_02_P(roleData)
            else this.war_plan_02()
        }
        else
        {
            this.plan_C1(BluePrint2)
        }
    }
    /* 2型战争应急预案模块，支持新role */
    public war_plan_02():void{
        if (!global.DicCreepFrameControl[this.name]) return
        var role = global.DicCreepFrameControl[this.name]
        for (var index in role)
        {
            if (!role[index].must) role[index].num = 0
        }
        global.DicCreepFrameControl[this.name] = role
    }

    /* 爬虫运行模块 */
    public FrameCreepWork():void{
        if (!global.DicCreepFrameControl[this.name]) return
        var creepRoleDic = global.DicCreepFrameControl[this.name]
        for (var index in Game.creeps)
        {
            let citizen = Game.creeps[index]
            if (citizen.memory.belong != this.name) continue
            loopA:
            for (var role_key in global.DicCreepFrameControl[this.name])
            {
                /* 由框架控制的 和 由任务系统控制的分开运行 */
                if (citizen.memory.role == creepRoleDic[role_key].work && citizen.memory.controlByFrame)
                {
                    if (creepRoleDic[role_key].fun) creepRoleDic[role_key].fun(citizen)
                    break loopA
                }
                if (citizen.memory.role == creepRoleDic[role_key].work && !citizen.memory.controlByFrame)
                {
                    citizen.HandMisson()
                    break loopA
                }
            }
        }
    }

    /* 运行房间内的stucture任务 */
    public StructureWork():void
    {
        var AllStructures =  this.getTypeStructure(['link','tower','terminal','lab','powerSpawn','observer']) as StructureLink[]
        for (var stru of AllStructures)
        {
            if (stru.HandMisson)
                stru.HandMisson()
        }
    }

    /* memory.creepNumData 与 role 之间的接口函数，实现爬虫数量手动控制 */
    public RoleChangeApi():void{
        if (!this.memory.creepNumData) this.memory.creepNumData = []
        if (!global.DicCreepFrameControl) global.DicCreepFrameControl = {}
        if (!global.DicCreepFrameControl[this.name]) global.DicCreepFrameControl[this.name] = {}
        // var role = global.DicCreepFrameControl[this.name]
        if (this.memory.creepNumData.length > 0)
        {
            for (var i of this.memory.creepNumData)
            {
                if (!global.DicCreepFrameControl[this.name][i.creeprole]) return
                global.DicCreepFrameControl[this.name][i.creeprole].num = i.num
            }
        }
    }

}